<template>
  <div class="main">
    <appLink :name="title"></appLink>
    <el-form :inline="true" :model="formInline" border class="demo-form-inline">
      <el-form-item>
        <el-input v-model="formInline.name" placeholder="姓名"></el-input>
      </el-form-item>
      <el-form-item>
        <el-select v-model="formInline.sex" placeholder="性别">
          <el-option label="男" value="男"></el-option>
          <el-option label="女" value="女"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="userList" class="el-icon-search">查询</el-button>
        <el-button type="primary" @click="adduser" class="el-icon-circle-plus-outline">新增</el-button>
        <el-button type="primary" @click="onSubmit" class="el-icon-refresh-left">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 列表页 -->
    <el-table :data="tableData" border stripe style="width: 100%">
      <el-table-column type="index" label="序号" width="50"></el-table-column>
      <el-table-column prop="username" label="账号" width="110"></el-table-column>
      <el-table-column prop="name" label="姓名" width="80"></el-table-column>
      <el-table-column prop="sex" label="性别" width="50"></el-table-column>
      <el-table-column prop="birthday" label="出生日期" width="150"></el-table-column>
      <el-table-column prop="phone" label="手机号码" width="150"></el-table-column>
      <el-table-column prop="address" label="地址"></el-table-column>
      <el-table-column label="头像" width="80">
        <template slot-scope="scope">
          <img :src="scope.row.pic" style="width:50px;height:50px;" />
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button type="warning" @click="editUser(scope.row)" :title="isAdd?'新增用户':'编辑用户'">编辑</el-button>
          <el-button type="danger" @click="delUser(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :page-sizes="[10, 20, 30, 40]"
      :page-size="pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    ></el-pagination>
    <!-- 新增表单 -->
    <el-dialog :title="isAdd?'新增用户':'编辑用户'" :visible.sync="dialogFormVisible" width="600px">
      <el-form
        :rules="rules"
        :model="formLabelAlign"
        label-position="right"
        label-width="100px"
        class="demo-ruleForm"
        ref="formLabelAlign"
      >
        <el-form-item label="账号" prop="username" v-if="isAdd">
          <el-input
            v-model="formLabelAlign.username"
            autocomplete="off"
            placeholder="请输入账号"
            style="width:300px"
          ></el-input>
        </el-form-item>
        <el-form-item label="真实姓名" prop="name">
          <el-input
            v-model="formLabelAlign.name"
            autocomplete="off"
            placeholder="请输入姓名"
            style="width:300px"
          ></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-select v-model="formLabelAlign.sex" placeholder="性别">
            <el-option label="女" value="女"></el-option>
            <el-option label="男" value="男"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="手机号码" prop="phone">
          <el-input
            v-model.trim="formLabelAlign.phone"
            autocomplete="off"
            style="width:300px"
            placeholder="请输入手机号码"
          ></el-input>
        </el-form-item>
        <el-form-item label="出生日期" prop="birthday">
          <el-date-picker
            v-model="formLabelAlign.birthday"
            format="yyyy 年 MM 月 dd 日"
            value-format="yyyy-MM-dd"
            type="date"
            placeholder="选择日期"
          ></el-date-picker>
        </el-form-item>
        <el-form-item prop="address" label="地址">
          <el-input
            v-model="formLabelAlign.address"
            autocomplete="off"
            style="width:300px"
            placeholder="请输入地址"
          ></el-input>
        </el-form-item>
        <el-form-item prop="pic" label="上传头像">
          <el-upload
            class="upload-demo"
            ref="upload"
            action="/dev-api/userMgr/adduser"
            :file-list="fileList"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :on-change="onChange"
            :before-remove="beforeRemove"
            :on-exceed="handleExceed"
            multiple
            :limit="1"
            name="photo"
            :auto-upload="false"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <!-- <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div> -->
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="isAdd ? add() : edit()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
// 二了吗UL框架的调用
import appLink from "@/components/link";

import usersApi from "@/api/usersApi";

export default {
  data() {
    var validatePsw = (rule, value, callback) => {
      let reg = /1[3-9]\d{9}/;
      if (reg.test(value) && value.length == 11) {
        callback();
      } else {
        callback(new Error("请输入正确的手机号码"));
      }
    };
     var validateUser = (rule, value, callback) => {
       let p =  usersApi.auditUsername(this.formLabelAlign.username)
           p.then(res=>{
            if(res.data.flag){
              callback();
            }else{
              callback(new Error("该账号已存在"))
            }
           }).catch((err) => {
             console.log(err)
           })
     }

    return {
      title: "用户管理",
      isAdd: true, //判断是要新增还是编辑
      formInline: {}, //查询条件
      tableData: [],
      page: 1,
      pagesize: 10,
      total: 0,
      // 新增表单
      form: {
        name: "",
        region: ""
      },
      rules: {
        username: [
          { validator: validateUser, trigger: 'blur' },
          { required: true, message: "账号不能为空", trigger: "blur" } //真实姓名不能为空
        ],
        name: [
          { required: true, message: "姓名不能为空", trigger: "blur" } //真实姓名不能为空
        ],
        phone: [
          {
            required: true,
            message: "手机号码不能为空",
            validator: validatePsw,
            trigger: "blur"
          }, //用户名不能为空
          { trigger: "blur" } //验证用户名是否存在
        ]
      },
      // 弹框显示或隐藏
      dialogFormVisible: false,
      // 对话框
      labelPosition: "rigth",
      formLabelAlign: {
        username:"",
        name: "",
        sex: "",
        phone: "",
        birthday: "",
        address: ""
      },
      fileList: []
    };
  },
  components: {
    appLink,
    usersApi
  },
  methods: {
    // 查询. 新增, 重置
    async userList() {
      try {
        let p = await usersApi.getUserList(
          this.page,
          this.pagesize,
          this.formInline
        );

        // 查到数据
        // console.log(p, p.data);
        if (p.data.flag) {
          this.tableData = p.data.data;
          this.total = p.data.total;
        } else {
          this.$message({
            message: "换个条件试试"
          });
        }
      } catch (err) {
        console.log(err);
      }
    },

    // 新增点击打开
    adduser() {
      this.dialogFormVisible = true;
      this.isAdd = true;
      this.fileList = [];

      this.$nextTick(() => {
        this.$refs["formLabelAlign"].resetFields();
        // this.$nextTick()它是一个异步事件，当渲染结束 之后 ，它的回调函数才会被执行
        // 弹出窗口打开之后 ，需要加载Dom, 就需要花费一点时间，我们就应该等待它加载完dom之后，再进行调用resetFields方法，重置表单和清除样式
        // this.$refs["formLabelAlign"].resetFields();
      });
    },
    // 重置
    onSubmit() {
      this.formInline = {};
      this.userList();
    },

    // 删除
    delUser(row) {
      // console.log(row._id);
      this.$confirm("是否删除", {
        confirmButtonText: "确定",
        cancelButtonText: "取消"
      })
        .then(() => {
          usersApi.deluser(row._id).then(res => {
            if (res.data.flag) {
              this.$message({
                message: "删除成功",
                type: "success"
              });
              this.userList();
            } else {
              this.$message({
                message: "删除失败",
                type: "error"
              });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },

    // 编辑
    editUser(row) {
      // console.log(row);
      this.dialogFormVisible = true;
      this.isAdd = false;
      this.formLabelAlign = row;
      this.fileList = [];
      // console.log(this.formLabelAlign,55555);
      
      let obj = {
        name:this.formLabelAlign.fileNames,
        url:this.formLabelAlign.img
      }
      this.fileList.push(obj);
    },
    // 确定编辑
    edit() {
      let form = new FormData();
      form.append("name", this.formLabelAlign.name);
      form.append("sex", this.formLabelAlign.sex);
      form.append("phone", this.formLabelAlign.phone);
      form.append("birthday", this.formLabelAlign.birthday);
      form.append("address", this.formLabelAlign.address);
      form.append("_id", this.formLabelAlign._id);
      this.fileList.forEach(file => {
        //接口那边：req.files
        form.append("photo", file.raw); //此处一定是append file.raw 上传文件只需维护fileList file.raw.name要加上
        form.append("fileNames", file.name);
      });
      usersApi.editUser(form).then(res=>{
        if(res.data.flag){
          // console.log(res)
          this.$message({
            message:"修改成功",
            type:"success"
          })
          this.dialogFormVisible = false;
          this.userList();
        }else{
          this.$message({
            message: "修改失败",
            type: "error"
          });
        }
      })
    },

    // 确定新增
    add() {
      this.$refs.formLabelAlign.validate(async res => {
        // console.log(res);
        if (res) {
          this.$refs.upload.submit();
          let form = new FormData();
          form.append("name", this.formLabelAlign.name);
          form.append("sex", this.formLabelAlign.sex);
          form.append("phone", this.formLabelAlign.phone);
          form.append("birthday", this.formLabelAlign.birthday);
          form.append("address", this.formLabelAlign.address);
          form.append("username", this.formLabelAlign.username)
          form.append("password","123456");
          this.fileList.forEach(file => {
            form.append("photo", file.raw);
            form.append("fileNames", file.name);
          });
          try {
            let p = await usersApi.addUser(form);
            if (p.data.flag) {
              this.$message({
                message: "添加成功",
                type: "success"
              });
              this.dialogFormVisible = false;
              this.userList();
            } else {
              this.$message({
                message: "添加失败",
                type: "error"
              });
            }
          } catch (err) {
            console.log(err);
          }
        } else {
          this.$message({
            message: "注意书写条件哦",
            type: "error"
          });
        }
      });
    },
    // 监听上传图片
    onChange(file, fileList) {
      this.fileList = fileList;
    },
    
    handleRemove(file, fileList) {
      //删除文件
      // console.log(file, fileList, 222);
      let url = file.url;
    },
    handlePreview(file) {
      console.log(file, 333);
    },
    //功能：选择图片超过规定提示
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 1 个文件，本次选择了 ${
          files.length
        } 个文件，共选择了 ${files.length + fileList.length} 个文件`
      );
    },
    //功能：删除图片前提示
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },

    // 每页多少条
    handleSizeChange(val) {
      this.pagesize = val;
      this.userList();
    },

    // 第几页
    handleCurrentChange(val) {
      this.page = val;
      this.userList();
    }
  },
  // 钩子
  created() {
    this.userList();
  }
};
</script>

<style scoped>
.demo-form-inline {
  margin-top: 20px;
}
</style>